<template>
  <div class="home-container">
    <div class="home-header">
      <h1>欢迎使用校园消防设备巡检管理系统</h1>
      <p class="subtitle">高效、安全的消防巡检工作平台</p>
    </div>
    
    <div class="home-stats">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon el-icon-device"></div>
            <div class="stat-content">
              <div class="stat-number">{{ deviceCount }}</div>
              <div class="stat-label">设备总数</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon el-icon-check"></div>
            <div class="stat-content">
              <div class="stat-number">{{ inspectionCount }}</div>
              <div class="stat-label">今日巡检</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon el-icon-warning"></div>
            <div class="stat-content">
              <div class="stat-number">{{ alertCount }}</div>
              <div class="stat-label">告警数量</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon el-icon-user"></div>
            <div class="stat-content">
              <div class="stat-number">{{ userCount }}</div>
              <div class="stat-label">在线用户</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    
    <div class="home-content">
      <div class="content-section">
        <div class="section-header">
          <h3>最近巡检任务</h3>
          <el-button type="primary" size="small" @click="goToTasks">查看全部</el-button>
        </div>
        <el-table :data="recentTasks" style="width: 100%">
          <el-table-column prop="taskName" label="任务名称"></el-table-column>
          <el-table-column prop="startTime" label="开始时间"></el-table-column>
          <el-table-column prop="status" label="状态">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status === 'completed' ? 'success' : scope.row.status === 'executing' ? 'warning' : 'info'">
                {{ scope.row.status === 'completed' ? '已完成' : scope.row.status === 'executing' ? '进行中' : '待执行' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="text" @click="viewTask(scope.row)">查看</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <div class="content-section">
        <div class="section-header">
          <h3>设备状态统计</h3>
        </div>
        <div class="chart-container">
          <div id="deviceStatusChart" class="device-status-chart"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import inspectionTaskApi from '@/api/inspection-task'
import statisticsApi from '@/api/data-statistics'
import alertApi from '@/api/sys-alert'
import deviceApi from '@/api/device'
import userApi from '@/api/sys-user'

export default {
  name: 'HomePage',
  data() {
    return {
      deviceCount: 0,
      inspectionCount: 0,
      alertCount: 0,
      userCount: 0,
      recentTasks: [],
      deviceStatusChart: null,
      deviceStatusData: {
        normal: 0,
        fault: 0,
        disabled: 0
      }
    }
  },
  created() {
    this.fetchHomeData()
  },
  
  mounted() {
    // 确保DOM已渲染后初始化图表
    this.$nextTick(() => {
      this.initDeviceStatusChart()
    })
    
    // 添加窗口调整监听
    window.addEventListener('resize', this.handleResize)
  },
  
  beforeDestroy() {
    // 清理图表实例和事件监听器
    if (this.deviceStatusChart) {
      this.deviceStatusChart.dispose()
    }
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    fetchHomeData() {
		// 调用API获取首页数据
		// 获取设备总数
			deviceApi.list({ size: 1 }).then(res => {
				if (res && res.data) {
					this.deviceCount = res.data.total || 0
				}
			}).catch(error => {
				console.error('获取设备总数失败:', error)
			})

		// 获取告警数量
			alertApi.list({ size: 1 }).then(res => {
				if (res && res.data) {
					this.alertCount = res.data.total || 0
				}
			}).catch(error => {
				console.error('获取告警数量失败:', error)
			})

		// 获取最近巡检任务和今日巡检数
			inspectionTaskApi.list({ size: 5, order_by: 'start_time', order_type: 'desc' }).then(res => {
				if (res && res.data) {
					this.recentTasks = res.data.records || []
				// 计算今日巡检任务数（简单模拟，实际应该在API查询参数中指定日期）
				const today = new Date().toLocaleDateString()
				this.inspectionCount = this.recentTasks.filter(task => {
					const taskDate = new Date(task.start_time || task.create_time || task.created).toLocaleDateString()
					return taskDate === today
				}).length
			}
		}).catch(error => {
			console.error('获取最近巡检任务失败:', error)
		})

		// 获取用户数量
			userApi.list({ size: 1 }).then(res => {
				if (res && res.data) {
					this.userCount = res.data.total || 0
				}
			}).catch(error => {
				console.error('获取用户数量失败:', error)
			})
		
		// 设置设备状态统计数据（使用模拟数据）
		this.deviceStatusData = {
			normal: 85,
			fault: 12,
			disabled: 3
		}
	},
	
	// 初始化设备状态图表
	initDeviceStatusChart() {
		try {
			const chartDom = document.getElementById('deviceStatusChart')
			if (chartDom) {
				this.deviceStatusChart = this.$echarts.init(chartDom)
				this.updateDeviceStatusChart()
			}
		} catch (error) {
			console.error('初始化设备状态图表失败:', error)
		}
	},
	
	// 更新设备状态图表
	updateDeviceStatusChart() {
		if (!this.deviceStatusChart) return
		
		const option = {
			title: {
				text: '设备状态分布',
				subtext: '',
				left: 'center',
				textStyle: {
					fontSize: 16,
					fontWeight: 'bold'
				}
			},
			tooltip: {
				trigger: 'item',
				formatter: '{a} <br/>{b}: {c} ({d}%)'
			},
			legend: {
				orient: 'vertical',
				left: 'left',
				data: ['正常', '故障', '停用']
			},
			series: [
				{
					name: '设备状态',
					type: 'pie',
					radius: ['40%', '70%'],
					avoidLabelOverlap: false,
					itemStyle: {
						borderRadius: 10,
						borderColor: '#fff',
						borderWidth: 2
					},
					label: {
						show: true,
						formatter: '{b}: {c} ({d}%)'
					},
					emphasis: {
						label: {
							show: true,
							fontSize: 14,
							fontWeight: 'bold'
						}
					},
					data: [
						{value: this.deviceStatusData.normal, name: '正常', itemStyle: {color: '#67c23a'}},
						{value: this.deviceStatusData.fault, name: '故障', itemStyle: {color: '#f56c6c'}},
						{value: this.deviceStatusData.disabled, name: '停用', itemStyle: {color: '#409eff'}}
					]
				}
			]
		}
		
		this.deviceStatusChart.setOption(option)
	},
	
	// 处理窗口大小调整
	handleResize() {
		if (this.deviceStatusChart) {
			this.deviceStatusChart.resize()
		}
	},
    goToTasks() {
      this.$router.push('/inspection/task')
    },
    viewTask(task) {
      this.$router.push(`/inspection/task/detail/${task.id}`)
    }
  }
}
</script>

<style scoped>
.home-container {
  padding: 20px;
}

.home-header {
  text-align: center;
  margin-bottom: 30px;
}

.home-header h1 {
  font-size: 28px;
  margin-bottom: 10px;
  color: #303133;
}

.subtitle {
  color: #909399;
  font-size: 16px;
}

.home-stats {
  margin-bottom: 30px;
}

.stat-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-icon {
  font-size: 32px;
  width: 60px;
  height: 60px;
  line-height: 60px;
  text-align: center;
  background: #ecf5ff;
  border-radius: 50%;
  color: #409eff;
  margin-right: 20px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.stat-label {
  color: #909399;
  font-size: 14px;
  margin-top: 5px;
}

.home-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.content-section {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.section-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.chart-container {
    height: 300px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .device-status-chart {
    height: 300px;
    width: 100%;
  }

@media (max-width: 768px) {
  .home-content {
    grid-template-columns: 1fr;
  }
}
</style>